<template>
    <div class="container">
        <!-- header -->
        <div class="header">
            <div>
                <p class="header-title">状态:</p>
                <el-select
                    v-model="value"
                    size="small"
                    @change="getTableData(1)"
                    placeholder="请选择">
                    <el-option
                        v-for="item in option"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"/>
                </el-select>
            </div>

            <div>
                <p class="header-title">任务项:</p>
                <el-input
                    v-model="keyword"
                    placeholder="输入任务项标题"
                    suffix-icon="el-icon-search"
                    size="small"
                    clearable
                    class="search-ipt"
                    @keyup.native.enter="getTableData(1)"/>
            </div>
        </div>

        <!-- table -->
        <el-table
            :data="tableData"
            height="100%"
            style="width: 100%;"
            border
        >
            <el-table-column
                label="序号"
                prop="id"
                width="100"
                align="center"
            />
            <el-table-column
                label="任务项标题"
                prop="task_title"
                show-overflow-tooltip
                :formatter="emptyFormatter"
                align="center"
            />
            <el-table-column
                label="EI分数"
                prop="task_score"
                show-overflow-tooltip
                :formatter="emptyFormatter"
                align="center"
            />
            <el-table-column
                label="任务说明"
                prop="task_info"
                show-overflow-tooltip
                :formatter="emptyFormatter"
                align="center"
            />
            <el-table-column
                label="状态"
                prop="task_status"
                show-overflow-tooltip
                :formatter="emptyFormatter"
                align="center"
            >
                <template slot-scope="scope">
                    <div v-if="scope.row.task_status == 1">已启用</div>
                    <div v-else>未启用</div>
                </template>
            </el-table-column>
            <el-table-column
                label="创建时间"
                prop="create_time"
                show-overflow-tooltip
                :formatter="emptyFormatter"
                align="center"
            >
                <template slot-scope="scope">
                    <span>{{ scope.row.create_time * 1000 | dateFormatter('yyyy/MM/dd HH:mm') }}</span>
                </template>
            </el-table-column>
            <el-table-column
                label="操作"
                show-overflow-tooltip
                :formatter="emptyFormatter"
                align="center"
            >
                <template slot-scope="scope">
                    <span
                        class="checkInfo"
                        v-if="scope.row.task_status == 0"
                        @click="fnUse(scope.row)">启用</span>
                    <span
                        class="checkInfo"
                        v-else-if="scope.row.task_status == 1"
                        @click="fnNotUse(scope.row)">不启用</span>
                    <span
                        class="checkInfo"
                        @click="fnEdit(scope.row)">编辑</span>
                </template>
            </el-table-column>
        </el-table>
        <!-- /table -->

        <!-- 详情弹窗 -->
        <el-dialog
            title="任务项"
            :visible.sync="dialogVisible"
            width="620px"
            :before-close="handleClose">
            <el-form
                ref="form"
                :model="form"
                label-width="80px">
                <p style="margin-bottom:15px;">修改任务项有可能会影响管培生分值统计，请谨慎修改！</p>
                <el-form-item
                    label="任务项："
                    class="dia_title">
                    <el-input
                        style="display:inline-block;"
                        v-model="task_title"
                        size="small"
                        clearbale
                        placeholder="请输入任务项标题"/>
                </el-form-item>
                <el-form-item
                    label="EI分数："
                    class="dia_title">
                    <el-input
                        style="display:inline-block;"
                        v-model="task_score"
                        size="small"
                        clearbale
                        placeholder="请输入EI分值"/>
                </el-form-item>
                <!-- banner跳转 -->
                <el-row class='row-flex'>
                    <el-form-item
                        class="task-form-item"
                        size="small"
                        label="跳转链接:"
                    >
                        <el-cascader
                            :props="{ expandTrigger: 'hover' }"
                            :placeholder="setJump"
                            size="small"
                            :filterable="true"
                            v-model="formData.app_action"
                            :options="linkSelectData"
                            @change="handleChange()"
                            ref="myCascader"
                            style="width:498px"
                        />
                    </el-form-item>
                </el-row>
                <el-form-item
                    size="small"
                >
                    <!-- 外链输入框 -->
                    <div
                        v-for="(item,index) in param"
                        :key="index"
                    >
                        <div v-if="item.type == 'text'">
                            <el-input
                                placeholder="请输入链接"
                                style="width: 300px"
                                v-model="formData.jump_url"
                                @input="getJump"
                                clearable
                            >
                                <template
                                    class="param"
                                    slot="prepend">{{ item.title }}</template>
                            </el-input>
                            <p style="display:inline-block;color:#999;margin-left:12px">*需要联系技术提供</p>
                        </div>
                    </div>
                    <!-- 外链输入框 -->

                    <!-- 内链选择框 -->
                    <div
                        v-for="(item,index) in paramCont"
                        :key="index"
                    >
                        <div
                            v-if="paramCont.length == 2 "
                            style="display:flex;marginBottom: 10px"
                        >
                            <p class="el-select-title">{{ item.title }}</p>
                            <el-select
                                v-model="list[index]"
                                filterable
                                placeholder="请选择"
                                @change="getLink"
                                style="marginLeft: -5px;width:239px"
                            >
                                <el-option
                                    v-for="item in options[index]"
                                    :key="item.value"
                                    :label="item.title"
                                    :value="item.value"/>
                            </el-select>
                            <p style="display:inline-block;color:#999;margin-left:12px">*需要联系技术提供</p>
                        </div>
                        <div
                            v-if="item.type == 'select' && paramCont.length == 1 "
                            style="display:flex;marginBottom: 10px"
                        >
                            <p class="el-select-title">{{ item.title }}</p>
                            <el-select
                                v-model="formData.jump_url"
                                filterable
                                placeholder="请选择"
                                @change="getJump"
                                style="marginLeft: -5px;width:239px"
                            >
                                <el-option
                                    v-for="item in options[index]"
                                    :key="item.value"
                                    :label="item.title"
                                    :value="item.value"/>
                            </el-select>
                            <p style="display:inline-block;color:#999;margin-left:12px">*需要联系技术提供</p>
                        </div>
                        <div v-if="item.type == 'text'">
                            <el-input
                                placeholder="请输入链接"
                                style="width: 300px"
                                v-model="formData.jump_url"
                                @input="getJump"
                                clearable
                            >
                                <template
                                    class="param"
                                    slot="prepend">{{ item.title }}</template>
                            </el-input>
                            <p style="display:inline-block;color:#999;margin-left:12px">*需要联系技术提供</p>
                        </div>
                    </div>
                    <!-- 内链输入框 -->
                </el-form-item>
                <!-- banner跳转 -->
                <el-form-item
                    label="任务说明："
                    label-width="82"
                    class="dia_textarea dia_title">
                    <el-input
                        style="display:inline-block;"
                        type="textarea"
                        size="mini"
                        :autosize="{ minRows: 2, maxRows: 4}"
                        maxlength="150"
                        show-word-limit
                        placeholder="请输入内容"
                        v-model="task_info"/>
                </el-form-item>
            </el-form>
            <span
                slot="footer"
                class="dialog-footer">
                <el-button
                    @click="dialogVisible = false"
                    size="small"
                >取 消</el-button>
                <el-button
                    type="primary"
                    size="small"
                    @click="fnEditTask">确 定</el-button>
            </span>
        </el-dialog>
        <!-- /详情弹窗 -->
    </div>
</template>

<script>
export default {
    data () {
        return {
            right:'left',
            form:{},
            task_info:'',
            task_score:'',
            task_title:'',
            dialogVisible:false,
            value:'',
            option:[
                {
                    value: '',
                    label: '全部'
                },
                {
                    value: '1',
                    label: '已启用'
                },
                {
                    value: '0',
                    label: '未启用'
                },
            ],
            keyword:"",
            tableData: [],
            page: {
                now_page: 1,
                total_count: 0,
                page_size: 0
            },
            formData: {
                app_action: '',
                jump_url: '',
                form_name: ''
            },
            setJump: '请选择',
            list: [],
            link: '',
            param: [],
            paramCont: [],
            options: [],
            linkSelectData: [],
            isapp: true
        };
    },
    watch: {
        dialogVisible (val) {
            if (!val) {
                this.isapp = true;
            }
        }
    },
    created(){
        this.setHeader();
        this.getTableData();
        this.getappAcion();
    },

    methods: {
        rowStyle () {
            return 'height: 100px';
        },

        /**
         * 设置表单header
         */
        setHeader () {
            this.$store.commit('SET_HEADER',[{title: "APP后台",},{title: '任务项'}]);
        },

        /**
         * 获取表格数据
         */
        getTableData (page) {
            this.$post('/student/stuagent_task%5Cget_list', {
                page_id: page || this.page.now_page,
                task_status: this.value,
                task_title: this.keyword,
            }, resp => {
                if(resp.code == 1){
                    this.tableData = resp.data.list;
                    this.page.now_page = resp.data.page.now_page;
                    this.page.total_count = resp.data.page.total_count;
                    this.page.page_size = resp.data.page.page_size;
                }
            });
        },

        /**
         * app行为数据处理
         */
        getappAcion () {
            let arr = [];
            let param = '';
            let val = '';

            this.$post('/student/app_action%5Cget_cascade_list', {
            }, resp => {
                if (resp.code == 1) {
                    resp.data.list.map((item,index)=>{
                        arr.push({
                            value: item.action,
                            label: item.title,
                            children: []
                        });
                        item.target_list.map((itm, idx) => {
                            val = {
                                target: itm.target,
                                param: []
                            };
                            itm.param_list.map((option,i)=> {
                                val.param.push({
                                    param: option.param,
                                    title: option.title,
                                    type: option.form_type
                                });
                            });
                            arr[index].children.push({
                                value: JSON.stringify(val),
                                label: itm.title
                            });
                        });
                    });
                }
                this.linkSelectData = arr;
            });
        },

        /**
         * app链接数据处理
         */
        handleChange () {
            let app_action = this.formData.app_action;
            let obj = JSON.parse(app_action[1]);
            let link = {
                action: '',
                target: '',
                param: {}
            };
            let param = [];

            this.formData.form_name = '';
            this.$set(this.formData, 'jump_url', '');

            if (app_action[0] == 'app_page') { //内部链接
                let param_list = obj.param;

                this.param = this.paramCont = this.list = [];

                if (param_list.length == 1) {
                    for(let i in param_list) {
                        param.push(
                            param_list[i]
                        );
                    }
                    this.list = [''];
                } else if (param_list.length == 2) {
                    param_list.map(item=>{
                        param.push({
                            type: 'select',
                            param: item.param,
                            title: item.title,
                            target: obj['target']
                        });
                    });
                    this.list = ['',''];
                }

                this.paramCont = param;

                if (this.paramCont.length == 0) {
                    this.$message({
                        type: 'warning',
                        message: '暂时不支持,延后添加',
                        center: true
                    });
                    return;
                }

                this.options = [];
                this.paramCont.map((item,index)=>{
                    if (item.type == 'select') {
                        this.$post('/student/app_action%5Cget_param_item_list',{
                            action: 'app_page',
                            target: obj['target'],
                            param: item.param
                        },resp => {
                            if (resp.code == 1 ) {
                                if (this.paramCont.length == 1) {
                                    this.options.push(
                                        resp.data.list
                                    );
                                } else if (this.paramCont.length == 2){ // 设置顺序
                                    if (item.param == 'form_no') {
                                        this.options.push(
                                            resp.data.list
                                        );
                                    }
                                    if (item.param == 'scene_key') {
                                        setTimeout(()=>{
                                            this.options.push(
                                                resp.data.list
                                            );
                                        },200);
                                    }
                                }
                            } else if (resp.code == 0) {
                                this.options = [];
                            }
                        });
                        link.param[[item['param']]] = this.formData.jump_url;
                    }
                    if (item.type == 'text') {
                        link.param[[item['param']]] = this.formData.form_name;
                    }

                    link.action = app_action[0];
                    link.target = obj['target'];
                });
            } else if (app_action[0] == 'link_outer') { //外部链接
                this.paramCont = [];
                this.ifSelect = 'text';
                this.param = obj.param;

                //链接赋值
                link = {
                    action: app_action[0],
                    target: obj['target'],
                    param: {
                        url : this.formData.jump_url
                    }
                };
            } else {
                return;
            }
            this.link = link;
        },

        /**
         * @abstract  单链接text_select处理
         */
        getJump (url) {
            let param = {};

            this.$set(this.formData, 'jump_url', url);
            for(let key in this.link['param']) {
                param[key] = url;
            }

            this.link['param'] = param;
            console.log(JSON.stringify(this.link), 'app_action');
        },

        /**
         * @abstract  双链接select处理
         */
        getLink () {
            let param = {};

            //保证param字段不重复，否则值会被覆盖
            this.paramCont.map((item,index)=>{
                param[item.param] = this.list[index];
            });

            this.link['param'] = param;
            console.log(JSON.stringify(this.link), 'app_action');
        },

        /**
         * 启用
         */
        fnUse(row){
            this.$confirm('启用该任务项前，请确保已与技术人员沟通获取其技术支持', '点击启用弹出', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$post('/student/stuagent_task%5Cset_status', {
                    task_status: 1,
                    id: row.id,
                }, resp => {
                    if(resp.code == 1){
                        this.$message({
                            type: 'success',
                            message: '启用成功',
                            duration: 1000
                        });
                        this.getTableData(1);
                    } else {
                        this.$message({
                            type: 'error',
                            message: '启用失败',
                            duration: 1000
                        });
                    }
                });
            }).catch(() => {});
        },

        /**
         * 不启用
         */
        fnNotUse(row){
            console.log(123);
            this.$confirm('不启用该任务项有可能会影响管培生分值统计，是否确认？', '点击取消启用弹出', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$post('/student/stuagent_task%5Cset_status', {
                    task_status: 0,
                    id: row.id,
                }, resp => {
                    if(resp.code == 1){
                        this.$message({
                            type: 'success',
                            message: '操作成功',
                            duration: 1000
                        });
                        this.getTableData(1);
                    } else {
                        this.$message({
                            type: 'error',
                            message: '操作失败',
                            duration: 1000
                        });
                    }
                });
            }).catch(() => {});
        },

        /**
         * 关闭弹窗
         */
        handleClose(){
            this.dialogVisible = false;
        },

        /**
         * 编辑按钮
         */
        fnEdit(row){
            this.dialogVisible = true;
            this.id = row.id;
            this.$post('/student/stuagent_task%5Cget',{
                id: row.id
            },resp=>{
                if (resp.code == 1) {
                    this.task_title = resp.data.task_title;
                    this.task_score = resp.data.task_score;
                    this.task_info = resp.data.task_info;
                    if (resp.data.app_action == '') {
                        return;
                    }

                    let app_action = JSON.parse(resp.data.app_action);
                    let app = [];

                    this.$post('/student/app_action%5Cget_cascade_list', {}, resp => {
                        if (resp.code == 1) {
                            resp.data.list.map(item => {
                                if (app_action.action == 'link_outer') {
                                    item.target_list.map(itm => {
                                        if (itm.target == app_action.target) {
                                            app.push(
                                                app_action.action,
                                                JSON.stringify({
                                                    target: app_action.target,
                                                    param: [{
                                                        param: itm.param_list[0].param,
                                                        title: itm.param_list[0].title,
                                                        type: itm.param_list[0].form_type
                                                    }]
                                                })
                                            );
                                            this.setApp_action(app,itm.param_list[0].title,app_action.param.url,itm.target);
                                        }
                                    });
                                }

                                if (app_action.action == 'app_page') {
                                    let length = Object.keys(app_action.param).length;

                                    app = [];
                                    app.push(
                                        app_action.action,{
                                            target: app_action.target,
                                            param: []
                                        }
                                    );
                                    item.target_list.map((itm,idx) => {
                                        if (itm.target == app_action.target) {
                                            itm.param_list.map((option,i) => {
                                                app[1].param.push({
                                                    param: option.param,
                                                    title: option.title,
                                                    type: option.form_type
                                                });
                                            });
                                        }
                                    });
                                    setTimeout(()=>{
                                        if (this.isapp) {
                                            this.setSelect_action(app,length,app_action.param);
                                            this.isapp = false;
                                        }
                                    },50);
                                } else {
                                    return;
                                }
                            });
                        }
                    });
                } else {
                    this.$message({
                        type: 'waring',
                        message: resp.msg,
                        center: true
                    });
                }
            });
        },

        /**
         * select
         */
        setSelect_action (app,length,url) {
            if (length == 1) {
                let list = JSON.parse(JSON.stringify(app));
                let param = JSON.stringify(app[1]);

                this.paramCont = [{
                    type: 'select',
                    title: list[1].param[0]['title']
                }];
                list[1] = param;
                this.formData.app_action = list;
                this.options = [];
                for(let i in url) {
                    this.$post('/student/app_action%5Cget_param_item_list',{
                        action: 'app_page',
                        target: JSON.parse(list[1]).target,
                        param: i
                    },resp => {
                        if (resp.code == 1 ) {
                            this.options.push(
                                resp.data.list,
                            );
                        } else if (resp.code == 0) {
                            this.options = [];
                        }
                    });
                    this.$set(this.formData, 'jump_url', url[i]);
                    this.link = {
                        "action":"app_page",
                        "target":list[1].target,
                        "param":{
                            [i]: url[i]
                        }
                    };
                }
            } else if (length == 2) {
                let data = JSON.parse(JSON.stringify(app));
                let params = JSON.stringify(app[1]);
                let current = [];

                app[1] = params;
                this.formData.app_action = app;
                this.paramCont = [];
                this.list = [];

                if (typeof(data[1]['param']) == 'object') {
                    data[1]['param'].map((item,index)=>{
                        this.paramCont.push({
                            type: 'select',
                            title: item.title,
                            param: item.param,
                            target: data[1].target
                        });
                    });
                }

                this.options = [];
                for(let i in url) {
                    this.$post('/student/app_action%5Cget_param_item_list',{
                        action: 'app_page',
                        target: data[1].target,
                        param: i
                    },resp => {
                        if (resp.code == 1 ) {
                            if (i == 'form_no') {
                                this.options.push(
                                    resp.data.list,
                                );
                            }
                            if (i == 'scene_key') {
                                setTimeout(()=>{
                                    this.options.push(
                                        resp.data.list,
                                    );
                                },200);
                            }
                        } else if (resp.code == 0) {
                            this.options = [];
                        }
                    });
                    this.link = {
                        action :"app_page",
                        target : data[1].target,
                        param :{
                            form_no: url[i],
                            scene_key: url[i]
                        }
                    };
                    this.list.push(url[i]);
                    console.log({list: this.list});
                }
            }
        },

        /**
         * link_outer
         */
        setApp_action (app,title,url,target) {
            this.formData.app_action = app;
            this.$set(this.formData, 'jump_url', url);
            this.param = [{
                type: 'text',
                title: title
            }];
            this.link = {"action":"link_outer","target":target,"param":{"url":url}};
        },
        // {"action":"app_page","target":"custom_form_custom_scene","param":{"form_no":"fm_5507cab254059","scene_key":"掌大精英可见"}}


        /**
         * 编辑任务项
         */
        fnEditTask(){
            this.dialogVisible = false;
            this.$post('/student/stuagent_task%5Csave', {
                task_title: this.task_title,
                id: this.id,
                task_info: this.task_info,
                task_score: this.task_score,
                app_action: JSON.stringify(this.link)
            }, resp => {
                if(resp.code == 1){
                    this.$message({
                        type: 'success',
                        message: '修改成功',
                        duration: 1000
                    });
                    this.getTableData(1);
                } else {
                    this.$message({
                        type: 'error',
                        message: '修改失败',
                        duration: 1000
                    });
                }
            });
        },

        /**
         * 过滤函数
         */
        emptyFormatter(row, column, val) {
            if (!val) {
                return '--';
            }
            return val;
        },
    }
};
</script>

<style lang="less" scoped>
    .container {
        padding: 15px;
        display: flex;
        flex-direction: column;
        position: relative;
        width: 100%;
        height: 100%;
        background: #fff;
        .operation-wrapper {
            display: flex;
            flex-direction: row-reverse;
            padding: 12px 23px;
            background-color: #fff;
        }
        .header {
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            &-title {
                display: inline-block;
                color: #262626;
                margin-left: 20px;
                margin-right: 5px;
            }
            .search-ipt {
                width: 260px;
            }
        }

        .pagination-wrapper {
            padding-top: 10px;
            .el-pagination {
                float: right;
                padding: 0;
                background-color: transparent;
            }
        }
    }
    .select{
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    .checkInfo{
        color: #409EFF;
        cursor: pointer;
    }
    .el-table{
        text-align: center;
    }
    .fontcolor{
        color: #409EFF;
        cursor: pointer;
    }
    .data-num{
        display: inline-block;
    }
    .input_row{
        width: 100%;
        margin-bottom: 20px;
    }
    .el-input{
        width: 100%;
    }
    .el-textarea{
        // width: 80%;
        vertical-align: middle;
    }
    .dia_title{
        position: relative;
    }
    .dia_title::before{
        content: '*';
        display:block;
        color: #f00;
        position: absolute;
        top: 16px;
        left: 0px;
    }
    .dia_textarea::before{
        left: -9px;
    }
    .el-form-item__error{
        left: 15%!important;
    }
    .el-select-title {
        display: inline-block;
        color: #909399;
        background: #F5F7FA;
        padding: 0 18px;
        border: 1px solid #DCDFE6;
        border-radius: 4px 0 0 4px;
        border-right: none;
        height: 32px;
        white-space: nowrap;
    }
</style>